package com.yunxi.service.mes.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.yunxi.core.base.Constant;
import com.yunxi.core.web.ApiResult;
import com.yunxi.core.web.ResponseUtil;
import com.yunxi.eai.pojo.esb.EsbVO;
import com.yunxi.eai.pojo.mes.CertificateOfConformityVO;
import com.yunxi.eai.pojo.mes.VehicleMftInfoVO;
import com.yunxi.eai.pojo.mes.VehicleTrackVO;
import com.yunxi.eai.service.mes.MesService;
import com.yunxi.hubToBaseData.pojo.VehicleCertReqVO;
import com.yunxi.hubToBaseData.service.Mes2BaseDataDubboService;
import com.yunxi.hubToBiz.pojo.HubProduceTracePlanVO;
import com.yunxi.hubToBiz.pojo.HubVehicleMftInfoVO;
import com.yunxi.hubToBiz.service.HubProduceTraceService;
import com.yunxi.model.eai.EaiLog;
import com.yunxi.model.eai.mes.MesCoq;
import com.yunxi.model.eai.mes.MesTail;
import com.yunxi.rocketmq.producer.EaiLogsProducer;
import com.yunxi.service.mes.MesCoqService;
import com.yunxi.service.mes.MesTailService;
import org.dozer.Mapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by Administrator on 2019/5/23.
 */
@Service
@Qualifier("mesServiceImpl")
public class MesServiceImpl implements MesService {
    private static final Logger logger = LoggerFactory.getLogger(MesServiceImpl.class);

    @Autowired
    @Qualifier("mesTailServiceImpl")
    MesTailService mesTailService;
    @Autowired
    @Qualifier("mesCoqServiceImpl")
    MesCoqService mesCoqService;
    @Autowired
    @Qualifier("hubProduceTraceServiceImpl")
    HubProduceTraceService hubProduceTraceServiceImpl;
    @Autowired
    private EaiLogsProducer eaiLogsProducer;
    @Autowired
    private Mapper dozerMapper;
    @Autowired
    private Mes2BaseDataDubboService mes2BaseDataDubboServiceImpl;
    @Override
    public ApiResult distributeMes(EsbVO esbVO) throws Exception {
        String serviceName = esbVO.getServiceName();
        ApiResult apiResult = null;
        if (serviceName.equals(Constant.MES_COQ)) {
            //合格证
            apiResult=saveVehicleCoq(esbVO);

        }else {
            apiResult= ResponseUtil.fail(500,"没有对应的业务接口!");
        }
        return apiResult;
    }


    //合格证
    private ApiResult saveVehicleCoq(EsbVO esbVO) {
        ApiResult apiResult = null;
        String reqBody = esbVO.getReqBody();
        JSONObject jsonObject = JSON.parseObject(reqBody);
        ArrayList<CertificateOfConformityVO> mesCoqList = JSON.parseObject(String.valueOf( jsonObject.get("data")), new TypeReference<ArrayList<CertificateOfConformityVO>>() {
        });
        EaiLog eaiLog=new EaiLog();
        eaiLog.setEsbEaiContent(reqBody);
        eaiLog.setRequestSendTime(new Date());
        eaiLog.setFlowDesc("ESB系统发送合格证给PMS系统");
        eaiLog.setSourceSystem(Constant.PMS);
        eaiLog.setRequestId(esbVO.getRequestId());
        eaiLog.setServiceName(esbVO.getServiceName());
        try {
          /*  //内部业务
            apiResult=ResponseUtil.ok();
            if (apiResult.getCode()==-1){
                eaiLog.setDisposeStatus(2);
            }*/
             SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
            List list=new ArrayList();
            for (int i = 0; i < mesCoqList.size(); i++) {
                CertificateOfConformityVO certificateOfConformityVO =  mesCoqList.get(i);
                VehicleCertReqVO vehicleCertReq = dozerMapper.map(certificateOfConformityVO,VehicleCertReqVO.class);
                vehicleCertReq.setCertPrintDate(sdf.parse(certificateOfConformityVO.getCertDate()));
                list.add(vehicleCertReq);
            }
            mes2BaseDataDubboServiceImpl.syncCert(list);
            eaiLog.setResponseReceiveTime(new Date());
            apiResult=ResponseUtil.ok();
            eaiLog.setPmsResultContent(JSONObject.toJSONString(apiResult));
        }catch (Exception e){
            apiResult=ResponseUtil.fail();
            eaiLog.setDisposeStatus(2);
            logger.error(e.getMessage(),e);
        }
      //  Message message = new Message(rocketConfig.getEaiLogTopic(), "eaiLog",(JSONObject.toJSONString(eaiLog)).getBytes() );
        try {
         //   SendResult send = eaiLogProducer.getProducer().send(message);
            eaiLogsProducer.sendMessage(JSONObject.toJSONString(eaiLog));
        }catch (Exception e){
            logger.error(e.getMessage(),e);
        }

        return apiResult;
    }

    //车辆跟踪
   /* private ApiResult saveVehicleTail(EsbVO esbVO) throws Exception {
        ApiResult apiResult = null;
        String reqBody = esbVO.getReqBody();
        JSONObject jsonObject = JSON.parseObject(reqBody);
        ArrayList<MesTail> mesTailList = JSON.parseObject(String.valueOf( jsonObject.get("data")), new TypeReference<ArrayList<MesTail>>() {
        });
        //数据存储
        //mesTailService.saveBatch(mesTailList);
        ArrayList<HubProduceTracePlanVO> list = new ArrayList<>();
      *//*  //遍历生成
        for (int i = 0; i < mesTailList.size(); i++) {
            HubProduceTracePlanVO hubStockInPlanVO = new HubProduceTracePlanVO();
            MesTail mesTail = mesTailList.get(i);
            if (mesTail.getZtp().equals("8000")) {
                hubStockInPlanVO.setZvin(mesTail.getZvin());
                hubStockInPlanVO.setZordNo(mesTail.getZordno());
                list.add(hubStockInPlanVO);
            }
        }*//*
        for (int i = 0; i < mesTailList.size(); i++) {
            HubProduceTracePlanVO stockInPlanVO=new HubProduceTracePlanVO();
            MesTail mesTail =  mesTailList.get(i);
            BeanUtils.copyProperties(mesTail,stockInPlanVO);
            list.add(stockInPlanVO);
        }
        //调用业务接口传递list
        String hubStockInPlan = JSONObject.toJSONString(list);
        EaiLog eaiLog=new EaiLog();
        eaiLog.setEsbEaiContent(hubStockInPlan);
        eaiLog.setRequestSendTime(new Date());
        eaiLog.setFlowDesc("EAI系统发送车辆VIN给PMS系统，生成入库单");
        eaiLog.setSourceSystem(Constant.PMS);
        eaiLog.setServiceName(Constant.MES_TAIL);
        eaiLog.setRequestId(esbVO.getRequestId());
        try {
            apiResult = hubProduceTraceServiceImpl.updateCarInfo(list);
            eaiLog.setResponseReceiveTime(new Date());
            eaiLog.setPmsResultContent(JSONObject.toJSONString(apiResult));
            if (apiResult.getCode()==-1){
                eaiLog.setDisposeStatus(2);
            }
        }catch (Exception e){
            logger.error(e.getMessage(),e);
            apiResult=ResponseUtil.fail();
            eaiLog.setDisposeStatus(2);
        }
        Message message = new Message(rocketConfig.getEaiLogTopic(), "eaiLog",(JSONObject.toJSONString(eaiLog)).getBytes() );
        try {
            SendResult send = eaiLogProducer.getProducer().send(message);
        }catch (Exception e){
            logger.error(e.getMessage(),e);
        }
        return apiResult;
    }*/
}
